<?php

namespace app\process;

use app\admin\app\model\Material;
use app\admin\app\model\Qiniu;
use GuzzleHttp\Client;
use Workerman\Crontab\Crontab;

class Task
{
    public function onWorkerStart()
    {
        // 每分钟执行一次
        new Crontab('0 */1 * * * *', function () {
            $materisl = Material::where('down', 0)->first();
//            print_r($materisl);
            if (empty($materisl)) {
                return;
            }
            $materisl->down = 1;
            $douyin = $materisl->getLink();
            echo $douyin;
            $url = base64_encode($douyin);
            $client = new Client();
            try {
                $response = $client->get("https://www.mxnzp.com/api/douyin/video?url={$url}&app_id=tmmljmobrwhhvhip&app_secret=LvXC1g7PLKRIRcUw53dH2BYqZnTHFl8o");
                $content = json_decode($response->getBody()->getContents(), true);
                if ($content['code']) {
                    // 设置请求头信息
                    $options = [
                        'http' => [
                            'method' => 'GET',
                            'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
                            'ignore_errors' => true // 忽略 HTTP 错误
                        ]
                    ];
                    // 创建上下文
                    $context = stream_context_create($options);
                    $cover = file_get_contents($content['data']['cover'], false, $context);
                    $video = file_get_contents($content['data']['url'], false, $context);
                    $qiniu = new Qiniu();
                    list($cover_data, $cover_err) = $qiniu->uploadDouyin($cover);
                    list($video_data, $video_err) = $qiniu->uploadDouyin($video);
                    if ($cover_err !== null || $video_err !== null) {
                        throw new \Exception('保存文件失败');
                    }
print_r($cover_data);
                    $materisl->cover = $cover_data['key'];
                    $materisl->path = $video_data['key'];
                    $materisl->down = 2;
                }
            } catch (\Exception $e) {
                $materisl->down = 3;
                echo '视频下载出错' . $e->getMessage() . "\n";
            }
            $materisl->save();
        });
    }

    protected function dir($filePath)
    {
        // 获取文件所在目录
        $directory = dirname($filePath);
        // 检查目录是否存在
        if (!is_dir($directory)) {
            // 尝试递归创建目录
            $result = mkdir($directory, 0777, true);
            if (!$result) {
                // 创建目录失败，输出错误信息
                echo "无法创建目录: $directory";
                return;
            }
        }
    }
}